<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="title" class="tl-dialog" width="1000px" @open="open" @close="close" top="10px" :append-to-body="true" :modal-append-to-body="true">
    <div style="padding-bottom:10px">
      <!-- 查询界面 -->
      <tl-list-search ref="search" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false">
        <template slot="search">
          <el-form-item label="里程碑及任务模板名称">
            <el-input v-model="queryParam.qry_milepost" placeholder="模板名称"></el-input>
          </el-form-item>
          <el-form-item label="里程碑及任务模板类型">
            <el-select v-model="templatetypelist" multiple placeholder="请选择模板类型" collapse-tags style="width:250px">
              <el-option v-for="item in codeModel.typeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </template>
        <template slot="button">
          <el-button type="primary" @click="unfold()">
            <template v-if="!isFold">全部展开</template>
            <template v-else>全部折叠</template>
          </el-button>
        </template>
      </tl-list-search>
      <!-- 列表界面 -->
      <div>
        <!-- 列表选择 -->
        <div class="table-alert-div" ref="selector">
          <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
            <template slot="title">
              已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRows.length }}</a>项&nbsp;&nbsp;
              <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
            </template>
          </el-alert>
        </div>
        <!--表格渲染-->
        <el-table class="tl-table" ref="mainTable" :height="tableHeight" v-loading="loading" :data="datas" @sort-change="doSortChange" row-key="id" border fit :row-class-name="doChangeRowClassName" @expand-change="expandChange" @select="selectFather" @select-all="selectFatherAll">
          <el-table-column type="expand">
            <template slot-scope="props">
              <div style="margin-left:102px;padding-right: 5px">
                <el-table class="tl-table" :ref="'taskTable' + props.row.rowno"  :data="props.row.tasklist" row-key="id" border fit @select="selectChild" :header-cell-class-name="leftheaderStyle">
                  <el-table-column type="selection" width="55px" :reserve-selection="true" ></el-table-column>
                  <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
                  <el-table-column prop="taskname" label="任务名称" min-width="200px" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column type="selection" :reserve-selection="true" width="55px" v-if="isSingleSelect === false "></el-table-column>
          <el-table-column prop="name" label="里程碑及任务模板名称" width="240px" sortable="custom" sort-by="name" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="deliverable" label="可交付成果" sortable="custom" sort-by="deliverable" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="disptype" label="模板类型" sortable="custom" sort-by="type" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="操作" width="80px" align="center" fixed="right" v-if="isSingleSelect === true">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-finished" @click="doSelectData(scope.row[fieldDefaultKey])">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div slot="footer" class="dialog-footer" v-if="isSingleSelect === false">
      <el-button type="text" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_ref_list } from '@tapui/mixins/mixin_ref_list'
/** 子组件 */
/** 工具类 */
import { queryDataCode } from '@tapui/api/dataCode'
import { validateNull } from '@tapui/utils/validate'
import { filterObjectNull } from '@tapui/utils/util'
import { getAction, putAction, postAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  components: {},
  mixins: [mixin_ref_list],
  data() {
    return {
      description: '按模板新增',
      // 默认Key字段名
      fieldDefaultKey: 'id',
      // 默认显示字段名
      fieldDefaultValue: 'name',
      // url配置
      url: {
        list: '/mpm/milePostTemplate/refList',
        insert: '/mpm/projectMilepost/insertFromMilePostTemplate',
        queryCodeList: '/mpm/milePostTemplate/dataCodeList'
      },
      // 排序参数
      sorterInfo: {
        sidx: 'sortcode',
        sord: 'asc'
      },
      // 分页参数
      pageInfo: {
        currentPage: 1,
        pageSize: 2000,
        pageSizes: [10, 50, 100],
        totalCount: 0
      },
      addFromPlan: false,
      codeModel: {},
      templatetypelist: [],
      selectFatherRow: new Set(),
      selectChildRow: new Set(),
      expands: [],
      // 默认折叠
      isFold: false
    }
  },
  props: {
    parentId: {
      type: [Number, String],
      required: true
    },
    projectinfo: {
    }
  },
  methods: {
    getQueryParams() {
      let param = {}
      Object.assign(param, this.queryParam, this.externalQueryParam, this.filtersInfo, this.sorterInfo)
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      param.qry_projectlevel = this.projectinfo.projectlevel
      param.qry_type = this.templatetypelist.join(',')
      param.qry_enabled = 1
      return filterObjectNull(param)
    },
    // 点击一键展开/折叠
    unfold() {
      this.isFold = !this.isFold
      this.$nextTick(() => {
        let table = this.$refs.mainTable
        table.data.forEach(item => {
          table.toggleRowExpansion(item, this.isFold)
        })
      })
    },
    /** 查询数据 */
    loadData(paramMap) {
      if (!this.url.list) {
        this.$tap.alert('请设置查询数据地址!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      // 查询条件
      var params = this.getQueryParams()
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
            this.$nextTick(() => {
              if (this.isSingleSelect === false) {
                if (validateNull(this.externalSelectedRowKeys) === false) {
                  let externalSelectedRowKeyArray = this.externalSelectedRowKeys.split(',')
                  this.datas.forEach((item) => {
                    if (typeof item[this.fieldKeyComputed] !== 'undefined' && externalSelectedRowKeyArray.includes(item[this.fieldKeyComputed].toString())) {
                      this.$refs.mainTable.toggleRowSelection(item)
                    }
                  })
                }
              }
              // 重载数据，防止表格高度变矮（element自带的BUG）
              this.$refs.mainTable.doLayout()
            })
          } else {
            this.$tap.alert(res.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    doConfirm() {
      let params = {}
      let milepostids = [...this.selectFatherRow].join(',')
      let taskids = [...this.selectChildRow].join(',')
      if (validateNull(milepostids)) {
        this.$tap.alert('请勾选需要插入的里程碑及任务！', 'warning')
      }
      this.$set(params, 'milepostids', milepostids)
      this.$set(params, 'taskids', taskids)
      this.$set(params, 'planid', this.parentId)
      this.$set(params, 'projectcode', this.projectinfo.projectcode)
      this.$set(params, 'projectname', this.projectinfo.projectname)
      postAction(this.url.insert, params).then(res => {
        if (res.success) {
          this.$tap.message(res.message, 'success')
          if (this.addFromPlan) {
            this.$parent.$parent.milepostLoadInfo()
          }
          this.$emit('refresh')
        } else {
          this.$tap.alert(res.message, 'warning')
        }
        this.saveLoading = false
      })
      this.visible = false
    },
    doQueryCodeRef() {
      if (this.url.queryCodeList) {
        getAction(this.url.queryCodeList, { enablemilepost: '1' }).then((res) => {
          if (res.success) {
            this.codeModel = res.result
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    expandChange(row, expandRows) {
      // 打开某一个页签，将页签下已选择的任务置为选中状态
      let childRowArr = [...this.selectChildRow]
      if (expandRows.indexOf(row) > -1) {
        row.tasklist.forEach(inner => {
          if (childRowArr.indexOf(inner.id) > -1) {
            this.$nextTick(() => {
              this.$refs['taskTable' + row.rowno].toggleRowSelection(inner, true)
            })
          }
        })
      }
      this.expands = expandRows
    },
    selectFather(selectedRows, row) {
      // 选中里程碑，将对应的任务全选,将对应任务存入任务set
      if (selectedRows.indexOf(row) > -1) {
        row.tasklist.forEach(inner => {
          this.selectChildRow.add(inner.id)
          if (this.$refs['taskTable' + row.rowno]) {
            this.$refs['taskTable' + row.rowno].toggleRowSelection(inner, true)
          }
        })
      } else {
      // 取消选中里程碑，将对应的任务全部取消选中,将任务移出任务set
        row.tasklist.forEach(inner => {
          this.selectChildRow.delete(inner.id)
          if (this.$refs['taskTable' + row.rowno]) {
            this.$refs['taskTable' + row.rowno].toggleRowSelection(inner, false)
          }
        })
      }
      this.selectFatherRow = new Set(selectedRows.map(row => row.id))
    },
    selectFatherAll(selectedRows) {
      // 全选，将对应任务全部选择，将任务存入任务set
      if (selectedRows.length > 0) {
        this.datas.forEach(row => {
          row.tasklist.forEach(inner => {
            this.selectChildRow.add(inner.id)
            if (this.$refs['taskTable' + row.rowno]) {
              this.$refs['taskTable' + row.rowno].toggleRowSelection(inner, true)
            }
          })
        })
      } else {
        this.datas.forEach(row => {
          row.tasklist.forEach(inner => {
            this.selectChildRow.delete(inner.id)
            if (this.$refs['taskTable' + row.rowno]) {
              this.$refs['taskTable' + row.rowno].toggleRowSelection(inner, false)
            }
          })
        })
      }
      this.selectFatherRow = new Set(selectedRows.map(row => row.id))
    },
    selectChild(selectedRows, row) {
      // 如果selectedRows > 0，任务对应的里程碑自动选择
      if (selectedRows.length > 0) {
        let milepostLine = this.datas.filter(item => item.id === Number(row.mileposttemplateid))[0]
        this.$refs.mainTable.toggleRowSelection(milepostLine, true)
        this.selectFatherRow.add(milepostLine.id)
      }
      // 如果row包含在selectedRows中，即为选中，否则为取消勾选
      if (selectedRows.indexOf(row) > -1) {
        this.selectChildRow.add(row.id)
      } else {
        this.selectChildRow.delete(row.id)
      }
    },
    leftheaderStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return 'seltAllbtnDis'
      }
    },
    /** 关闭 */
    close() {
      // 初始化列表，防止再次进入时加载脏数据
      this.doClearSelected()
      this.selectFatherRow = new Set()
      this.selectChildRow = new Set()
      this.expands = []
    }
  },
  created() {
    this.doQueryCodeRef()
  }
}
</script>

<style lang="scss" scoped>
::v-deep .seltAllbtnDis .cell {
    visibility: hidden;
  }
</style>

